package org.khd.org.service.impl;

import org.khd.org.domain.Department;
import org.khd.org.mapper.DepartmentMapper;
import org.khd.org.query.DepartmentQuery;
import org.khd.org.service.IDepartmentService;
import org.khd.base.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void insertDep(Department department) {
        //维护path路径
        /*
        * 1.用户会选择一个parent或者null
        * 2.如果父级部门有值，查询父级部门
        * */
        departmentMapper.insertDep(department);
        department.setCreateTime(new Date());
        if (department.getParent() == null){
            department.setPath("/" + department.getId());
        }else {
            Department parent = departmentMapper.queryDepById(department.getParent().getId());
            department.setPath(parent.getPath() + "/" + department.getId());
        }
        departmentMapper.updateDep(department);
    }

    @Override
    @Transactional
    public void updateDep(Department department) {
        if (department.getParent() == null){
            department.setPath("/" + department.getId());
        }else {
            Department parent = departmentMapper.queryDepById(department.getParent().getId());
            department.setPath(parent.getPath() + "/" + department.getId());
        }
        departmentMapper.updateDep(department);
    }

    @Override
    @Transactional
    public void deleteDepById(Long id) {
        departmentMapper.deleteDepById(id);
    }

    @Override
    public Department queryDepById(Long id) {
        return departmentMapper.queryDepById(id);
    }

    @Override
    public List<Department> queryDepAll() {
        return departmentMapper.queryDepAll();
    }

    @Override
    public PageList<Department> queryDepPage(DepartmentQuery query) {
        //用来查询Department数据的总条数
        Long total = departmentMapper.queryDepCount(query);
        //用来查询Department每页的数据
        List<Department> list = departmentMapper.queryDepPage(query);
        return new PageList<>(total, list);
    }

    @Override
    public List<Department> queryDepTree() {
        return departmentMapper.queryDepTree();
    }

    @Override
    public void patchDeleteDep(List<Long> ids) {
        departmentMapper.patchDeleteDep(ids);
    }
}
